// This file is part of SyncStar, free software released under GPL v2.
package com.syncstar;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import org.json.JSONObject;

/** Interactive page with random buttons and other UI elements for debugging. */
public class DebugActivity extends Activity {
  @SuppressWarnings({"UnusedDeclaration"})
  private static final String TAG = WelcomeActivity.class.getSimpleName();

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GlobalReceiver.onActivityCreate(this);

    setContentView(R.layout.debug_layout);
    setTitle(R.string.debug_title);
    TextView tv = (TextView) findViewById(R.id.smstext);

    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");

    tv.setText(accounts[0].name + "\n" + getThreadsInfo());
    findViewById(R.id.buttonshow).setOnClickListener(
        new View.OnClickListener() { public void onClick(View v) { showSmses(); } });
    findViewById(R.id.buttoncount).setOnClickListener(
        new View.OnClickListener() { public void onClick(View v) { countSmses(); } });
    findViewById(R.id.buttonadd).setOnClickListener(
        new View.OnClickListener() { public void onClick(View v) { addSms(); } });
    findViewById(R.id.buttonsync).setOnClickListener(
        new View.OnClickListener() { public void onClick(View v) { syncSmses(); } });
  }

  void showSmses() {
    JSONObject reqData = SmsUtils.getPhoneSmsData(this, null);
    TextView tv = (TextView) findViewById(R.id.smstext);
    tv.setText(reqData.toString());
  }

  void countSmses() {
    final int count = smsGetMessageCount(false, "");
    final TextView tv = (TextView) findViewById(R.id.smstext);
    tv.setText(count + "");
    final String email = getSharedPreferences("config", 0).getString("email", "");
    final String authToken = getAuthToken(this, email);
    final String msg = "email=" + email + " authToken=" + authToken;
    Log.e(TAG, "CONNX authToken " + msg);
    tv.setText(count + "\n\n" + msg);
  }

  static String getAuthToken(final Context context, final String email) {
    final AccountManager accountManager = AccountManager.get(context);
    final String authTokenType = "oauth2:https://www.googleapis.com/auth/userinfo.email";
    Account account = email.length() == 0 ? null : SyncService.getAccount(context, email);
    if (account == null)
      return null;
    AccountManagerFuture<Bundle> result =
         context instanceof Activity ?
         accountManager.getAuthToken(account, authTokenType, null, (Activity)context, null, null) :
         accountManager.getAuthToken(account, authTokenType, true, null, null);
    String authToken;
    try {
      Bundle bundle = result.getResult();
      authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
    } catch (Exception e) {
      e.printStackTrace();
      // If the internet is not connected: java.io.IOException: null.
      return "ERROR: get: " + e.getClass() + ": " + e.getMessage();
    }
    if (authToken == null || authToken.length() == 0) {
      return "ERROR: Missing auth token.";
    }

    // Invalidate it so we can get a fresh one.
    accountManager.invalidateAuthToken(account.type, authToken);
    result =
         context instanceof Activity ?
         accountManager.getAuthToken(account, authTokenType, null, (Activity)context, null, null) :
         accountManager.getAuthToken(account, authTokenType, true, null, null);
    try {
      Bundle bundle = result.getResult();
      authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
    } catch (Exception e) {
      e.printStackTrace();
      // If the internet is not connected: java.io.IOException: null.
      return "ERROR: get: " + e.getClass() + ": " + e.getMessage();
    }
    if (authToken == null || authToken.length() == 0) {
      return "ERROR: Missing auth token.";
    }

    return authToken;
  }

  @SuppressWarnings({"RedundantCast"})
  String getThreadsInfo() {
    Class telephonyThreads;
    try {
      telephonyThreads = Class.forName("android.provider.Telephony$Threads");
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("getThreadProviderUri", e);
    }
    StringBuilder sb = new StringBuilder();
    try {
      sb.append("\nCONTENT_URI=");  // "content://sms-mms/conversations".
      sb.append(((Uri)telephonyThreads.getField("CONTENT_URI").get(null)).toString());
      sb.append("\n_ID=");  // "_id"
      sb.append((String)telephonyThreads.getField("_ID").get(null));
      sb.append("\nDATE=");  // "_date"
      sb.append((String)telephonyThreads.getField("DATE").get(null));
      sb.append("\nMESSAGE_COUNT=");  // "message_count"
      sb.append((String)telephonyThreads.getField("MESSAGE_COUNT").get(null));
      sb.append("\nRECIPIENT_IDS=");  // "recipient_ids"
      sb.append((String)telephonyThreads.getField("RECIPIENT_IDS").get(null));
      sb.append("\nSNIPPET=");  // "snippet"
      sb.append((String)telephonyThreads.getField("SNIPPET").get(null));
      sb.append("\nSNIPPET_CHARSET=");  // "snippet_cs"
      sb.append((String)telephonyThreads.getField("SNIPPET_CHARSET").get(null));
      sb.append("\nREAD="); // "read"
      sb.append((String)telephonyThreads.getField("READ").get(null));
      sb.append("\nERROR=");  // "error"
      sb.append((String)telephonyThreads.getField("ERROR").get(null));
      sb.append("\nHAS_ATTACHMENT=");  // "has_attachment"
      sb.append((String)telephonyThreads.getField("HAS_ATTACHMENT").get(null));
    } catch (IllegalAccessException e) {
      throw new RuntimeException("getThreadId", e);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException("getThreadProviderUri", e);
    }
    return sb.toString();
  }

  void addSms() {
    final ContentValues values = new ContentValues();
    values.put("body", "Árvíztűrő tükörfúrógép.");
    values.put("address", "+123456");
    values.put("type", SmsUtils.MESSAGE_TYPE_INBOX);
    //values.put(SmsConsts.PROTOCOL, getHeader(message, Headers.PROTOCOL));
    //values.put(SmsConsts.SERVICE_CENTER, getHeader(message, Headers.SERVICE_CENTER));
    values.put("date", System.currentTimeMillis() + "");
    values.put("thread_id", SmsUtils.getOrCreateThreadId(this, "addSms"));
    values.put("read", "0");
    //  PrefStore.getMarkAsReadOnRestore(mContext) ? "1" : getHeader(message, Headers.READ));
    final Uri uri = getContentResolver().insert(SmsUtils.SMS_PROVIDER, values);
    int count = smsGetMessageCount(false, "");
    TextView tv = (TextView) findViewById(R.id.smstext);
    tv.setText("Added SMS " + uri.toString() + "\nNew count: " + count);
  }
    void syncSmses() {
    long startedAt = System.currentTimeMillis();
    final TextView tv = (TextView) findViewById(R.id.smstext);
    final int[] oldCount = new int[] { 0 };
    final int[] newCount = new int[] { 0 };
    // Querying once takes about 60ms for 328 messages on a Nexus One.
    // Populating takes about 400ms.
    // TODO: Is the database slow or is the SMS content provider slow?
    tv.setText("Querying.");
    SmsUtils.iterPresenceTable(this, new SmsUtils.PresenceEntryReceiver() {
      public void receivePresenceEntry(String address, String body, long date, int type) {
        ++oldCount[0];
      }
    });
    tv.setText("Populating.");
    SmsUtils.populatePresenceTable(this, -1);
    tv.setText("Querying again.");
    SmsUtils.iterPresenceTable(this, new SmsUtils.PresenceEntryReceiver() {
      public void receivePresenceEntry(String address, String body, long date, int type) {
        ++newCount[0];
      }
    });
    tv.setText("PresenceEntry oldCount=" + oldCount[0] + " newCount=" + newCount[0] +
               "\ndurationMs=" + (System.currentTimeMillis() - startedAt));
  }

  int smsGetMessageCount(Boolean unreadOnly, String folder) {
    Uri uri = SmsUtils.buildFolderUri(folder);
    int result;
    String selection = unreadOnly ? "read = 0" : "";
    Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null) {
      result = cursor.getCount();
      cursor.close();
    } else {
      result = 0;
    }
    return result;
  }

}